import Flutter
import UIKit
import LarkSSOSDK
import Toast;

public class LarkAuthPlugin: NSObject, FlutterPlugin,LarkSSODelegate {

    var loginResult : FlutterResult?;

    // 实现 LarkSSODelegate 协议的回调方法
    public func lkSSODidReceive(response: LarkSSOSDK.SSOResponse) {
        print("lkSSODidReceive");
        // 处理响应结果
        response.safeHandleResult { (code) in
            print("Success: \(code)");
            // 将成功结果传递给 Dart 代码
            loginResult?(code);
        } failure: { (error) in
        // 处理失败结果
            getUpVC()?.view.makeToast("\(error.code)");
            var  errorMessage:String = "";
            switch (error.code) {
              case -1:
                errorMessage = "状态码校验失败，非当前SDK请求的响应";
                break;
              case -2:
                errorMessage = "没有获得有效的授权码";
                break;
              case -3:
                errorMessage = "用户取消授权";
                break;
              case -4:
                errorMessage = "跳转飞书失败";
                break;
              case -5:
                errorMessage = "授权失败";
                break;
              case -6:
                errorMessage = "请求参数错误";
                break;
              default:
                errorMessage = "授权失败";
                break;
            }
            print("Failure: \(error.code)");
            getUpVC()?.view.makeToast(errorMessage);
             // 将错误信息传递给 Dart 代码
            loginResult?(FlutterError(
                code: "\(error.code)",
                message:errorMessage,
                details: nil
            ));
        }
    }

  // 注册 Flutter 插件
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "lark_auth", binaryMessenger: registrar.messenger())
    let instance = LarkAuthPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
    registrar.addApplicationDelegate(instance)
  }

  // 获取当前展示的视图控制器
  func getUpVC() -> UIViewController? {
    let rootVC = UIApplication.shared.keyWindow?.rootViewController
    return rootVC
  }

  // 实现 FlutterPlugin 协议的方法，处理 Flutter 调用
  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    print(call.method);

    switch call.method {
      case "startSSOVerify":
        let args = call.arguments as? [String: Any]
        let appId = args?["appId"] as! String
        let language = args?["language"] as! String
        // 注册应用
        LarkSSOSDK.LarkSSO.register(apps: [
            App(server: .feishu, appId: appId, scheme: appId.replacingOccurrences(of: "_", with: ""))
        ])
        // 设置语言
        LarkSSOSDK.LarkSSO.setupLang(language)
        let request: SSORequest = .feishu
        request.scope = args?["scopeList"] as! [String]
        loginResult = result;
        // 发送认证请求
        LarkSSOSDK.LarkSSO.send(request: request, viewController: getUpVC() ,delegate: self)
        break;
      default:
        result(FlutterMethodNotImplemented)
    }
  }

  // 实现 application(_:open:options:) 方法，处理应用的 URL Scheme
  public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
      return LarkSSO.handleURL(url)
  }

}




